package com.example.jobback.intercept;

import com.example.jobback.config.AuthConfig;
import com.example.jobback.intercept.common.CommonInterceptService;
import com.example.jobback.po.Recruiter;
import com.example.jobback.po.Seeker;
import com.example.jobback.util.CACHEUtil;
import com.example.jobback.util.TLUtil;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.concurrent.TimeUnit;

import static com.example.jobback.util.RedisConstants.*;
import static java.time.LocalTime.now;


/**
 * @ClassName: RecruiterIntercept
 * @Description:招聘者拦截器
 * @Author: lhb
 * @Date: 2025/5/10
 */
@Component
@Slf4j
public class RecruiterIntercept implements HandlerInterceptor {


    private final CACHEUtil cacheUtil;


    private final AuthConfig authConfig;


    private final CommonInterceptService commonInterceptService;

    public RecruiterIntercept(CommonInterceptService commonInterceptService, CACHEUtil cacheUtil, AuthConfig authConfig) {
        this.commonInterceptService = commonInterceptService;
        this.cacheUtil = cacheUtil;
        this.authConfig = authConfig;
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler){
        String token=request.getHeader("Authorization");
        //跨服务，提前验证防止response重复设置
        if(commonInterceptService.checkCrossToken(token, response)) return true;
        Recruiter recruiter = null;
        try {
            recruiter = commonInterceptService.checkToken(token, response, authConfig.getJwtRecruiterSecret(), RECRUITER_KEY, Recruiter.class);
        } catch (Exception e) {
            //基本不可能于response设置http状态码冲突
            throw new RuntimeException(e);
        }
        if(recruiter == null) return false;
        Long userId=recruiter.getUserId();
        TLUtil.set(TLUtil.USER_ID,userId);
        TLUtil.set(TLUtil.R,recruiter);
        cacheUtil.expire(RECRUITER_KEY+userId.toString(),RECRUITER_TTL, TimeUnit.DAYS);
        log.info("招聘者拦截："+recruiter.getUserId().toString());
        return true;
    }


    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        TLUtil.remove(TLUtil.R);
        TLUtil.remove(TLUtil.USER_ID);
    }
}
